package com.wanmait.bootdemo.controller;

import com.wanmait.bootdemo.util.JSONResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

//@ControllerAdvice
@RestControllerAdvice
public class CommonControllerAdvice {

    @ExceptionHandler(Exception.class)
    //@ResponseBody
    public Object processException(Exception e, HttpServletRequest request)
    {
        System.out.println(isAjax(request)+"isAjax.......");
        if(isAjax(request))
        {
            System.out.println("isAjax......");
            return JSONResult.errorException(e.getMessage());
        }
        else
        {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("exception",e);
            modelAndView.addObject("url",request.getRequestURL());
            modelAndView.setViewName("error");
            return modelAndView;
        }
    }
    public boolean isAjax(HttpServletRequest request)
    {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }
}
